package com.travel.utils;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author slient
 */
@ConfigurationProperties(prefix = "qiniu")
@Component
@Data
public class QiNiuTools {

    private String accesskey;
    private String secketkey;

    //空间名
    private String bucket;

    //外链域名
    private String url;

    //返回图片的地址
    public String upload(MultipartFile file) { //mvc提供的上传解析器，file就是上传对象
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        // 指定分片上传版本
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString();

        try {
            //把上传对象转为字节数组
            //"hello qiniu cloud".getBytes("utf-8");
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accesskey, secketkey);
            String upToken = auth.uploadToken(bucket);
            //使用工具类实现上传
            Response response = uploadManager.put(uploadBytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
            //返回外链地址+图片名称
            return url+key;
        } catch (Exception ex) {
            //ignore
            ex.printStackTrace();
        }
        return "";
    }
}
